package com.example.forestmanagement.utils;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.StringRes;

/**
 * @author: Administrator
 * @date: 2023/4/8
 * @Description:
 */
public class T {
    private static Application context;

    public static void init(Application context) {
        T.context = context;
    }

    /**
     * @param msg
     */
    public static void show(String msg) {
        show(msg, Toast.LENGTH_SHORT);
    }

    public static void show(@StringRes int str) {
        show(context.getResources().getString(str), Toast.LENGTH_SHORT);
    }

    /**
     * @param msg
     * @param duration
     */
    public static void show(String msg, int duration) {
        if (!TextUtils.isEmpty(msg)) {
            if (isMainThread()) {
                Toast.makeText(context, msg, duration).show();
            } else {
                new Handler(Looper.getMainLooper()).post(() ->
                        Toast.makeText(context, msg, duration).show());
            }
        }
    }

    /**
     * 在service里使用Toast需要出现在一个线程的消息队列中....
     *
     * @param msg
     * @param duration
     */
    public static void showService(final String msg, final int duration) {
        show(msg, duration);
    }

    /**
     * 在service里使用Toast需要出现在一个线程的消息队列中....
     *
     * @param msg
     */
    public static void showService(final String msg) {
        showService(msg, Toast.LENGTH_SHORT);
    }

    /**
     * 支持字符串或字符串资源id
     *
     * @param obj 可传字符串或字符串资源id
     * @return
     */
    public static String parseString(Context context, Object obj) {
        if (obj != null) {
            if (obj instanceof String) {
                return obj.toString();
            } else if (obj instanceof Integer) {
                return context.getString((Integer) obj);
            }
        }
        return null;
    }

    private static boolean isMainThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }
}
